package com.imooc.common.plan.adapter;

import com.imooc.common.plan.handler.DefaultPlanHandler;
import com.imooc.common.plan.handler.SupportsHandler;
import com.imooc.common.plan.service.AbstractPlanService;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;

/**
 * 计划操作适配器(使用策略模式)
 */
@Component
public class DefaultPlanServiceAdapter implements ApplicationContextAware {
    /**
     * 计划服务处理器集合
     */
    private List<AbstractPlanService> defaultPlanServices;

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        defaultPlanServices = new ArrayList<>(applicationContext.getBeansOfType(AbstractPlanService.class).values());
    }

    /**
     * 根据计划类型获取通用计划处理器
     */
    public DefaultPlanHandler getDefaultPlanHandler(Integer type) {
        return supportsHandler(type,defaultPlanServices);
    }

    /**
     * 根据计划类型选择出 支持的服务类型
     */
    private <T extends SupportsHandler> T  supportsHandler(Integer type, List<T> handlerList){
        for (T createPlanHandler : handlerList) {
            if (createPlanHandler.supportsHandler(type)){
                return createPlanHandler;
            }
        }
        return null;
    }

}
